<?php

namespace app\controllers;

use Yii;
use yii\web\Response;
use app\services\SspService;
use app\services\ReportService;
use app\services\PackService;
use app\services\CreativeService as cs;
use app\utils\GEO as geo;
use app\utils\HttpUtil as U;
use app\services\ModifyService;
use app\models\ResourceApp;

class SolutionController extends AuthController
{
    public $currentHeader = 'header-campaign';
    public $currentNav = 'solution-nav';
    public $pageTitle = '';

    public function init() {
        parent::init();
        // $campaignService = new \app\services\CampaignService();
        // $campaigns = $campaignService->getAll('Campaign', ['advertiser_id'=>$this->S('advertiser_id')]);
        // $this->campaigns = $campaigns;
        $this->templates = $this->getAll('CreativeTemplate', ['is_sl' => 1]);
        $serv = new \app\services\CreativeService();
        $this->mobiles = $this->getAll('MobileDeviceBrand', ['status' => 1]);
    }

    public function actionSolutionList() {
        $this->pageTitle = $this->t('solution', 'Solution List');
        $this->campaign_id = $this->I('campaign_id');
        $this->brandShow = true;
        $this->filter = $this->isAllowedSeeShows();
        return $this->show();
    }

    // public function actionNewSolution() {
    //     $this->pageTitle = $this->t('solution', 'New Mobile Solution - Basic');
    //     return $this->show();
    // }

    public function actionNewSolutionBasic() {
        $this->pageTitle = $this->t('solution', 'New Mobile Solution - Basic');
        $this->S('solution_id', null);
        $this->subTitle = $this->t('solution', 'New Solution');
        $camId = $this->service->getCampaignId();
        if ($camId) {
            $this->bidCampaignId = $camId;
            $bidCampaign = $this->M('Campaign', $camId);
            $this->bidCampaign = $bidCampaign;
            $this->S('advertiser_id',$bidCampaign['advertiser_id']);
        }
        $this->budgetRange = $this->service->getSolutionTotalBudgetRange($camId);
        $this->channels = $this->service->getAdNetwork();
        $this->pmps = $this->service->getPmps();
        $this->campaigns = $this->service->getSolutionCampaigns();
        return $this->show();
    }

    public function actionNewSolutionTarget() {
        $this->pageTitle = $this->t('solution', 'New Solution - Condition');
        $solution = $this->M('Solution', $this->I('solution_id'));
        $this->clientAudienceType = $this->service->getAudienceWithClient();
        $this->solution = $solution;
        $this->bidCampaign = $this->M('Campaign', $solution['campaign_id']);
        $this->setConditionDicts();
        return $this->show();
    }

    /**
     * 相应的广告位分类等下拉选项
     */
    public function setConditionDicts() {
        $this->adspaceCategory = $this->service->getAdspaceCategory();
        $instruments = $this->service->sort2LevelCates('Instrument', 'description');
        $this->instruments = $instruments;
        $topInstruments = $this->service->getTopInstrument();
        $this->topInstruments = $topInstruments;

        $this->adspaces = $this->service->getAdspaces($this->S('ad_network_id'));
        $this->frequencyTypes = $this->service->getFrequencyTypes();
        $this->weather = $this->service->getWeatherTypes();
        $this->weatherId = $this->service->getWeatherIdLevel();
        $retarget = $this->service->getRetargetTypes();
        $this->retargets = $retarget;

        $sites = $this->service->getRetargetSite(1);
        $this->sites = $sites;

        if ($this->I('solution_id')) {
            $this->solution = $this->M('Solution', $this->I('solution_id'));
        }
    }

    /**
     * 根据type id 获取标签
     */
    public function actionGetRetargetSite() {
        $retargetTypeId = $this->I('retarget_type_id');
        $data = $this->service->getRetargetSite($retargetTypeId);
        $this->jsonReturn(['data' => $data]);
    }

    public function actionNewSolutionResource() {
        $this->pageTitle = $this->t('solution', 'New Solution - Resource');
        $this->adNetworkId = $this->S('ad_network_id');
        $this->adspaces = $this->service->getAdspaces(0, 2);
        // $this->adnetworks = $this->getAll('AdNetwork', ['ad_network_type' => 1]);
        $this->adnetworks = $this->service->getAllAdNetWork();
        $solution = $this->M('Solution', $this->I('solution_id'));
        $this->solution = $solution;
        $this->pmpAdspaces = $this->service->getPmpAdspaces($solution['pmp_guid']);
        $packService = new PackService();
        $packs = $packService->getPackLevel(1);
        $wapPacks = $packService->getPackLevel(2);
        $this->packs = $packs;
        $this->wapPacks = $wapPacks;
        $this->siteUrl = $this->getSiteBaseUrl();
        return $this->show();
    }

    public function actionNewSolutionCreative()  {
        $this->pageTitle = $this->t('solution', 'New Solution - Creative');
        $this->solution_id = $this->I('solution_id');
        $this->solution = $this->M('Solution', $this->I('solution_id'));
        $this->filter = $this->isAllowedSeeShows();
        return $this->show();
    }

    public function actionNewSolutionBidding() {
        $this->pageTitle = $this->t('solution', 'New Solution - Bidding');
        $this->pmps = $this->service->getPmps();
        $id = $this->I('solution_id');
        !$id && $id = $this->I('id');
        $this->S('solution_id', $id);
        $solution = $this->M('solution', $id);
        if (!$solution) $this->NG($this->t('solution', 'Need solution id'));
        $this->S('ad_network_id', $solution['ad_network_id']);
        $campaignId = $solution['campaign_id'];
        $this->channel = $this->service->getAdNetwork(['id' => $solution['ad_network_id']]);
        $this->bidCampaignId = $campaignId;
        $this->bidCampaign = $this->M('Campaign', $campaignId);
        $budget = $this->service->getSolutionTotalBudgetRange($campaignId, $id);
        $this->budgetRange = $budget;
        $this->solution = $solution;
        $report = new ReportService; 
        $this->solutionDateRange = $report->getReportSolutionDateRange($solution['id']);
        // $this->campaigns = $campaigns;
        $this->campaigns = $this->service->getSolutionCampaigns($solution['id']);
        list($floorPrice, $ceilingPrice) = $this->service->getSolutionPackPriceRange($solution['id']);
        $this->floorPrice = $floorPrice;
        $this->ceilingPrice = $ceilingPrice;
        return $this->show();
    }

    public function actionNewSolutionHandle() {
        $_POST['name'] = $this->dropBlank($_POST['name']);
        if (!$_POST['id'])  $this->service->checkSolutionDate();
        $oldSolution = [];
        if ($_POST['id']) $oldSolution = $this->M('solution', $_POST['id']);
        $oldSolutionStatus = '';
        if(!empty($oldSolution['status'])){
            $oldSolutionStatus = $oldSolution['status'];
        }
        list($max, $min) = $this->service->getSolutionTotalBudgetRange($this->I('campaign_id')); 
        $totalBudget = $this->I('budget');
	    if ($totalBudget > $max || $totalBudget < $min || $totalBudget <= 0) {
	        $this->NG($this->t('solution', 'Save solution failed, budget not correct!'));
	    }

        if ($this->I('is_pmp') == 0) {
            unset($_POST['pmp_guid']);
            unset($_POST['pmp_price']);
        }
        !$_POST['id'] && $data['advertiser_id'] = $this->S('advertiser_id');
        $data['last_update'] = date('Y-m-d H:i:s');
        if(isset($_POST['old_budget']) && $_POST['budget'] != $_POST['old_budget']) $_POST['solution_audit'] = 0;
        $solution = $this->save('solution', $data);
        if($oldSolution){
            $modifyService = new ModifyService();
            $modifyService -> saveModify($oldSolution,$solution,'Solution',['id'],['last_update']);
            $this->service->updateSolutionNameOnSolutionCreativeMap($solution);
        }
        if(is_array($solution)) {
            $this->S('solution_id', $solution['id']);
            $this->S('ad_network_id', $solution['ad_network_id']);
            // 预先占位 solution condition type if new created
            if (!$this->I('id')) {
                $conditionType = $this->I('condition_class_type');
                !$conditionType && $condition_type = 'is_for_mobile';
                $this->service->takeUpConditionTypes($solution['id'], $conditionType);
            } 
            $this->service->savePmpAdspaces($oldSolution, $solution);
            $ready = $this->service->readySolution($this->I(),$oldSolutionStatus);
            $change = false;
            if ($oldSolution) {
                if ($oldSolution['budget'] != $solution['budget'] 
                    || $oldSolution['start_date'] != $solution['start_date']
                    || $oldSolution['end_date'] != $solution['end_date']) {
                    $change = true;
                }
            }
            // 新建或者影响每日预算的时候需要重新计算balance
            if (!$_POST['id'] || $change) {
                $this->service->initBalance($solution['id'], $change);
            }
            $this->s('solution_id', $solution['id']);
            $this->OK($this->t('solution', 'Solution basic attributes saved successfully!'), '', $solution);
        }
        $this->NG($this->t('solution', 'Solution basic attributes save failed!'));
    }

    public function actionNewSolutionTargetHandle() {
        $solutionId = $this->I('solution_id');
        if (!$solutionId) $solutionId = $this->I('solution_id');
        $this->service->saveConditions($solutionId, 'mobile');
        $this->OK($this->t('solution', 'Solution condition saved successfully!'), '', ['id' => $solutionId]);
    }

    public function actionNewPcSolutionTargetHandle() {
        $solutionId = $this->I('solution_id');
        if (!$solutionId) $solutionId = $this->I('solution_id');
        $this->service->saveConditions($solutionId, 'display');
        $this->OK($this->t('solution', 'Solution condition saved successfully!'), '', ['id' => $solutionId]);
    }

    public function actionGetAd() {
        $service = new SspService('vamaker');
        $service->syncAdspace('bannerAdspace');
        $service->syncAdspace('videoAdspace');
    }

    public function actionNewSolutionResourceHandle() {
        $ad_network_id = $this->I('ad_network_id');
        $solutionId = $this->I('solution_id');
        $this->service->saveConditionAdspace($solutionId);
        $this->service->saveConditionAdspaceAdnetwork($solutionId);
        $this->service->updateSolutionTime($solutionId);
        $this->OK($this->t('solution', 'Solution resource saved successfully!'), '', ['id' => $solutionId]);
        $this->NG($this->t('solution', 'Solution resource saved failed!'));
    }

    public function actionNewPcSolutionResourceHandle() {
        $ad_network_id = $this->I('ad_network_id');
        $solutionId = $this->I('solution_id');
        $this->service->saveConditionAdspace($solutionId);
        $this->service->saveConditionAdspaceAdnetwork($solutionId);
        $this->service->updateSolutionTime($solutionId);
        $this->OK($this->t('solution', 'Solution resource saved successfully!'), '', ['id' => $solutionId]);
        $this->NG($this->t('solution', 'Solution resource saved failed!'));
    }

    public function actionNewSolutionBiddingHandle() {
        $ready = $this->service->readySolution($this->I());
        $solutionId = $this->S('solution_id');
        $this->service->updateSolutionTime($solutionId);
        $this->OK($this->t('solution', 'Save done!'), '', ['id' => $solutionId]);
    }

    public function actionAddWebSolutionCreative () {
        $this->pageTitle = $this->t('solution', 'New Solution - New Web Creative');
        $adnetworkId = $this->S('ad_network_id');
        $service = new cs();
        $this->sizes = $service->getAvailableCreativeSize('MobileAdspace', '', $this->I('solution_id'), 'web');
        $this->categories = $service->getAllCategories($adnetworkId);
        $this->solutionId = $this->I('solution_id');
        return $this->showAjax();
    }

    public function actionAddAppSolutionCreative () {
        $this->pageTitle = $this->t('solution', 'New Solution - New App Creative');
        $adnetworkId = $this->S('ad_network_id');
        $service = new cs();
        $solutionId = $this->I('solution_id');
        //$sizes = $service->getAvailableCreativeSize('MobileAdspace', '', $solutionId, 'app');
        $bwList = $this->service->getConditionBWList($solutionId, 'is_for_mobile');
        $conditions = $this->service->getConditionsKey($solutionId, 'is_for_mobile');
        $sizes = $service->getTargetedAppAllowedSizes($conditions['ConditionAdspace'], $bwList['ConditionAdspace']);
        $this->sizes = $sizes;
        $this->formats = $service->getTargetedAdspaceFormats($conditions['ConditionAdspace'], $bwList['ConditionAdspace']);
        $this->categories = $service->getAllCategories($adnetworkId);
        $this->solutionId = $this->I('solution_id');
        return $this->showAjax();
    }

    public function actionAddMobileVideoSolutionCreative () {
        $this->pageTitle = $this->t('solution', 'New Solution - New Mobile Video Creative');
        $adnetworkId = $this->S('ad_network_id');
        $service = new cs();
        $this->sizes = $service->getAvailableCreativeSize('MobileVideoAdspace', '', $this->I('solution_id'), 'video');
        $this->categories = $service->getAllCategories($adnetworkId);
        $this->solutionId = $this->I('solution_id');
        return $this->showAjax();
    }

    public function actionEditWebSolutionCreative () {
        $this->pageTitle = $this->t('solution', 'Edit Solution - Edit Web Creative');
        $adnetworkId = $this->S('ad_network_id');
        $service = new cs();
        $this->sizes = $service->getAvailableCreativeSize('Adspace', $adnetworkId, $this->I('solution_id'));
        $this->categories = $service->getAllCategories($adnetworkId);
        $this->solutionId = $this->I('solution_id');
        return $this->showAjax();
    }

    public function actionEditAppSolutionCreative () {
        $this->pageTitle = $this->t('solution', 'Edit Solution - Edit App Creative');
        $adnetworkId = $this->S('ad_network_id');
        $service = new cs();
        $this->vsizes = $service->getAvailableCreativeSize('VideoAdspace', $adnetworkId, $this->I('solution_id'));
        $this->categories = $service->getAllCategories($adnetworkId);
        $this->solutionId = $this->I('solution_id');
        return $this->showAjax();
    }

    public function actionGetAudienceCategory() {
        $id = $this->I('node');
        $cates = $this->service->getAudienceCategory($id); 
        echo $cates;
    }

    public function actionSolutionWebCreativePreview () {
         $this->creativePreview();
    }

    public function actionSolutionBasicEdit ($pc=false) {
        $this->pageTitle = $this->t('solution', 'Edit Solution - Basic');
        $this->pmps = $this->service->getPmps();
        $id = $this->I('solution_id');
        !$id && $id = $this->I('id');
        $this->S('solution_id', $id);
        $solution = $this->M('solution', $id);
        if (!$solution) $this->NG($this->t('solution', 'Need solution id'));
        $this->S('ad_network_id', $solution['ad_network_id']);
        // $campaigns = $this->service->getAll('Campaign', ['advertiser_id'=>$this->S('advertiser_id')]);
        $campaignId = $solution['campaign_id'];
        $this->channel = $this->service->getAdNetwork(['id' => $solution['ad_network_id']]);
        $this->bidCampaignId = $campaignId;
        $this->bidCampaign = $this->M('Campaign', $campaignId);
        $budget = $this->service->getSolutionTotalBudgetRange($campaignId, $id);
        $this->budgetRange = $budget;
        $this->solution = $solution;
        $report = new ReportService; 
        $this->solutionDateRange = $report->getReportSolutionDateRange($solution['id']);
        // $this->campaigns = $campaigns;
        $this->campaigns = $this->service->getSolutionCampaigns($solution['id']);
        //if ($pc) return $this->show('pcSolutionBasicEdit');
        return $this->show();
    }

    public function actionSolutionTargetEdit () {
        $this->pageTitle = $this->t('solution', 'Edit Solution - Condition');
        $this->setConditionDicts();
        $solutionId = $this->I('solution_id');
        $solution = $this->M('Solution', $solutionId);
        $this->solution = $solution;
        $cityRank = $this->service->getRankCities();
        $this->clientAudienceType = $this->service->getAudienceWithClient();
        $this->cityRank = $cityRank;
        $this->allAudienceCategory = $this->service->getAllAudienceCategories();
        if ($solutionId) {
            $this->S('solution_id', $solutionId);
            $weekday_slot = $this->M('Solution', $solutionId)['weekday_slot'];
            $weekday_slot = explode(',', $weekday_slot);
            $this->pauseWeekday = array_diff([0,1,2,3,4,5,6], $weekday_slot);
            $bwList = $this->service->getConditionBWList($solutionId);
            $this->bwList = $bwList;
            $conditions = $this->service->getConditionsKey($solutionId, 'is_for_mobile');
            $this->conditions = $conditions;
            $weather = array_shift($conditions['ConditionWeather']);
            $weather = str_replace(';', ',', $weather);
            $this->targetedWeather = explode(',', $weather);
            $this->bidCampaign = $this->M('Solution', $this->I('solution_id'));
            $audience = $conditions['ConditionAudience'];
            !$audience && $audience[0]['audience_type_id'] = '';
            $targetedAudience = explode(',', $audience[0]['audience_type_id']);
            $this->targetedAudience = $targetedAudience;
        }
        return $this->show();
    }

    public function actionGetCampaignAttributes() {
        $campaignId = $this->I('campaign_id');
        $attr = $this->service->getCampaignAttributes($campaignId);
        $this->jsonReturn($attr);
    }

    public function actionSolutionResourceEdit () {
        $this->pageTitle = $this->t('solution', 'Edit Solution - Resource');
        $solutionId = $this->I('solution_id');
        $this->adNetworkId = $this->S('ad_network_id');
        $conditions = $this->service->getConditionsKey($solutionId, 'is_for_mobile');
        $this->bwList = $this->service->getConditionBWList($solutionId, 'is_for_mobile');
        $this->conditions = $conditions;
        //$this->adspaces = $this->service->getAdspaces(0, 2);
        $solution = $this->service->M('Solution', $this->I('solution_id'));
        $this->solution = $solution;
        //$this->pmpAdspaces = $this->service->getPmpAdspaces($solution['pmp_guid']);
        // $this->adnetworks = $this->getAll('AdNetwork', ['ad_network_type' => 1]);
        $this->adnetworks = $this->service->getAllAdNetWork();
        $this->solutionAdnets = array_column($this->getAll('ConditionAdspaceAdnetwork', ['solution_id' => $solutionId, 'status' => 1]) , 'adnetwork');
        $solutionAdspaceType = array_column($this->getAll('ConditionAdspaceAdnetwork', ['solution_id' => $solutionId, 'status' => 1]) , 'is_whitelist');
        $this->solutionAdspaceType = array_pop($solutionAdspaceType);
        $packService = new PackService();
        $packs = $packService->getPackLevel(1);
        $wapPacks = $packService->getPackLevel(2);
        $this->packs = $packs;
        $this->wapPacks = $wapPacks;
        $adIds = $conditions['ConditionAdspace'];
        $targetedApps = $this->service->getAppIdsOnAdspaceId($adIds);
        $all = $this->service->getIsTargetedAllApps($targetedApps);
        $this->isAll = $all;
        $solutionWapOrApp = 1;
        if (isset($targetedApps[0]) && isset($targetedApps[0]['app_id'])) {
            $solutionWapOrApp = $targetedApps[0]['app_id'];
            $solutionWapOrApp = ResourceApp::find()->select(['type'])
                ->where(['id' => $solutionWapOrApp])->scalar();
        }
        $targetedAppNicks = array_column($targetedApps, 'capp_id');
        $targetedAppIds = array_column($targetedApps, 'app_id');
        $this->solutionWapOrApp = $solutionWapOrApp;
        $this->targetedApps = $targetedAppNicks;
        $this->targetedAppIds = $targetedAppIds;
        //echo '<pre>';
        //print_r($solutionWapOrApp);
        //print_r(ResourceApp::find()->select(['type', 'id'])->where(['id' => $targetedAppIds])->asArray()->all());
        //exit;
        $this->siteUrl = $this->getSiteBaseUrl();
        return $this->show();
    }

    public function actionSolutionCreativeEdit () {
        $this->pageTitle = $this->t('solution', 'Edit Solution - Creative');
        $this->S('solution_id', $this->I('solution_id'));
        $solution = $this->M('Solution', $this->I('solution_id'));
        $this->solution = $solution;
        $creative = $this->service->getUserCreatives($solution);
        $this->creative = $creative;
        if ($this->I('type') == 'unlink') {
            $solutionId = $this->I('solution_id');
            $creativeId = $this->I('id');
            if (!is_numeric($solutionId) || !is_numeric($creativeId)) {
                $this->NG($this->t('solution', 'Need solution or creative id!'));
            }
            $unbind = $this->service->unbindCreative($solutionId, $creativeId);
            $this->service->updateSolutionTime($solutionId);
            if ($unbind) $this->OK($this->t('solution', 'Unbind creative successfully!'));
        }
        $this->filter = $this->isAllowedSeeShows();
        return $this->show();
    }

    public function actionGetSolutionCreatives() {
        $solutionId = $this->S('solution_id');
        !$solutionId && $solutionId = $this->I('solution_id');
        $crts = $this->service->getSolutionCreatives($solutionId);
        $this->jsonReturn(['data' => $crts]);
    }

    public function actionSolutionBiddingEdit () {
        $this->pageTitle = $this->t('solution', 'Edit Solution - Bidding');
        $this->pmps = $this->service->getPmps();
        $id = $this->I('solution_id');
        !$id && $id = $this->I('id');
        $this->S('solution_id', $id);
        $solution = $this->M('solution', $id);
        if (!$solution) $this->NG($this->t('solution', 'Need solution id'));
        $this->S('ad_network_id', $solution['ad_network_id']);
        // $campaigns = $this->service->getAll('Campaign', ['advertiser_id'=>$this->S('advertiser_id')]);
        $campaignId = $solution['campaign_id'];
        $this->channel = $this->service->getAdNetwork(['id' => $solution['ad_network_id']]);
        $this->bidCampaignId = $campaignId;
        $this->bidCampaign = $this->M('Campaign', $campaignId);
        $budget = $this->service->getSolutionTotalBudgetRange($campaignId, $id);
        $this->budgetRange = $budget;
        $this->solution = $solution;
        $report = new ReportService; 
        $this->solutionDateRange = $report->getReportSolutionDateRange($solution['id']);
        // $this->campaigns = $campaigns;
        $this->campaigns = $this->service->getSolutionCampaigns($solution['id']);
        list($floorPrice, $ceilingPrice) = $this->service->getSolutionPackPriceRange($solution['id']);
        $this->floorPrice = $floorPrice;
        $this->ceilingPrice = $ceilingPrice;
        return $this->show();
    }

    public function actionGetAllSolutions() {
        $solutions = $this->service->getAllSolutions();
        $this->jsonReturn(['data' => $solutions]);
    }

    public function actionNewSolutionCreativeHandle() {
        $this->OK($this->t('solution', 'Save done!'));
    }

    /**
     * 更新 solution 状态
     */
    public function actionListOperateHandle() {
        $solutionId = $this->I('solution_id');
        $type = $this->I('type');
        if ($this->service->updateSolutonStatus($solutionId, $type))
        {
            $this->OK($this->t('solution', 'Action done!'));
        }
        $this->NG($this->t('solution', 'Action failed!'));
    }

    public function actionBindSolutionCreativeHandle() {
        $solutionId = $this->I('solution_id');
        $creativeIds = $this->I('creative_id');
        if (!$creativeIds) $creativeIds = [];
        $this->service->bindCreative($solutionId, $creativeIds); 
        $this->service->updateSolutionTime($solutionId);
        $this->OK($this->t('solution', 'Bind creative successfully!'));
    }

    // $type must equal 'GET' or 'POST'
    public function curl_request_async($url, $params, $type='GET') {
        if(is_array($params)) {
            foreach ($params as $key => &$val) {
                if (is_array($val)) $val = implode(',', $val);
                $post_params[] = $key.'='.urlencode($val);
            }
            $post_string = implode('&', $post_params);
        } else {
            $post_string = '';
        }

        $parts=parse_url($url);
        $fp = @fsockopen($parts['host'], isset($parts['port'])?$parts['port']:80,
            $errno, $errstr, 30);

        if (!$fp ) {
            // $msg = "ERROR:  $errno - $errstr";
            // $path1 = debug_backtrace();
            // $class = strrchr($path1[1]['class'], '\\');
            // $fun = $path1[1]['function'];
            // $category = substr($class, 1).'_'.$fun;
            // $this->log($msg, $category);
        } else {
            // Data goes in the path for a GET request
            if('GET' == $type) $parts['path'] .= '?'.$post_string;
            $out = "$type ".$parts['path']." HTTP/1.1\r\n";
            $out.= "Host: ".$parts['host']."\r\n";
            $out.= "Content-Type: application/x-www-form-urlencoded\r\n";
            $out.= "Content-Length: ".strlen($post_string)."\r\n";
            $out.= "Connection: Close\r\n\r\n";
            // Data goes in the request body for a POST request
            // if ('POST' == $type && isset($post_string)) $out.= $post_string;
            fwrite($fp, $out);
            fclose($fp);
        }
    }

    public function actionGetPmpPrice() {
        $guid = $this->I('newValue');
        $this->service->getPmpPrice($guid);
    }

    public function actionNewPcSolutionBasic() {
        $this->pageTitle = $this->t('solution', 'New PC Solution - Basic');
        $this->subTitle = $this->t('solution', 'New Solution');
        $camId = $this->service->getCampaignId();
        $this->S('solution_id', null);
        if ($camId) {
            $this->bidCampaignId = $camId;
            $bidCampaign = $this->M('Campaign', $camId);
            $this->bidCampaign = $bidCampaign;
            $this->S('advertiser_id',$bidCampaign['advertiser_id']);
        }
        $this->budgetRange = $this->service->getSolutionTotalBudgetRange($camId);
        $this->channels = $this->service->getAdNetwork();
        $this->pmps = $this->service->getPmps();
        $this->campaigns = $this->service->getSolutionCampaigns();
        return $this->show();
    }

    public function actionNewPcSolutionTarget() {
        $this->pageTitle = $this->t('solution', 'New PC Solution - Condition');
        $solution = $this->M('Solution', $this->I('solution_id'));
        $this->solution = $solution;
        $this->setConditionDicts();
        $this->clientAudienceType = $this->service->getAudienceWithClient();
        $youku = $this->service->getYouTuChannels('优酷');
        $tudou = $this->service->getYouTuChannels('土豆');
        $youTu = ['优酷频道' => $youku, '土豆频道' => $tudou];
        $this->youTu = ['优酷频道' => $youku, '土豆频道' => $tudou];
        return $this->show();
    }

    public function actionNewPcSolutionResource() {
        $this->pageTitle = $this->t('solution', 'New PC Solution - Resource');
        $this->adNetworkId = $this->S('ad_network_id');
        $solution = $this->M('Solution', $this->I('solution_id'));
        $this->solution = $solution;
        $this->adspaces = $this->service->getAdspaces(0, 1);
        // $this->adnetworks = $this->getAll('AdNetwork', ['ad_network_type' => 1]);
        $this->adnetworks = $this->service->getAllAdNetWork();
        $this->pmpAdspaces = $this->service->getPmpAdspaces($solution['pmp_guid']);
        return $this->show();
    }
    
    public function actionNewPcSolutionCreative()  {
        $this->pageTitle = $this->t('solution', 'New PC Solution - Creative');
        $this->solution_id = $this->I('solution_id');
        $this->solution = $this->M('Solution', $this->I('solution_id'));
        return $this->show();
    }

    public function actionNewPcSolutionBidding() {
        $this->pageTitle = $this->t('solution', 'New PC Solution - Bidding');
        return $this->show();
    }

    public function actionAddSolutionCreative () {
        $this->pageTitle = $this->t('solution', 'New Solution - Creative');
        $this->solutionId = $this->I('solution_id');
        $adnetworkId = $this->S('ad_network_id');
        $service = new cs();
        $this->sizes = $service->getAvailableCreativeSize('Adspace', '', $this->I('solution_id'));
        $this->categories = $service->getAllCategories($adnetworkId);
        return $this->showAjax();
    }

    public function actionAddVideoSolutionCreative () {
        $this->pageTitle = $this->t('solution', 'New Solution - New Video Creative');
        $this->solutionId = $this->I('solution_id');
        $adnetworkId = $this->S('ad_network_id');
        $service = new cs();
        $this->sizes = $service->getAvailableCreativeSize('VideoAdspace', '', $this->I('solution_id'));
        $this->categories = $service->getAllCategories($adnetworkId);
        return $this->showAjax();
    }

    public function actionAddCpeBannerSolutionCreative () {
        $this->pageTitle = $this->t('solution', 'New Solution - New CPE Creative');
        $this->solution_id = $this->I('solution_id');
        $adnetworkId = $this->S('ad_network_id');
        $service = new cs();
        $this->sizes = $service->getAvailableCreativeSize('Adspace', '', $this->I('solution_id'),'cpe-banner');
        $this->categories = $service->getAllCategories($adnetworkId);
        return $this->showAjax();
    }

    public function actionAddCpeVideoSolutionCreative () {
        $this->pageTitle = $this->t('solution', 'New Solution - New CPE Creative');
        $sid = $this->I('solution_id');
        !$sid && $sid = $this->I('solution_id');
        $this->solutionId = $sid;
        $this->solution_id = $sid;
        $cid = $this->I('creative_id');
        !$cid && $cid = $this->I('id');
        $this->creative_id = $cid;
        $adnetworkId = $this->S('ad_network_id');
        $service = new cs();
        $this->sizes = $service->getAvailableCreativeSize('VideoAdspace', '', $this->I('solution_id'));
        $this->categories = $service->getAllCategories($adnetworkId);
        return $this->showAjax();
    }

    public function actionAddOverlaySolutionCreative () {
        $this->pageTitle = $this->t('solution', 'New Solution - New Overlay Creative');
        $this->solutionId = $this->I('solution_id');
        $adnetworkId = $this->S('ad_network_id');
        $service = new cs();
        $this->sizes = $service->getAvailableCreativeSize('VideoAdspace', '', $this->I('solution_id'), 'overlay');
        $this->categories = $service->getAllCategories($adnetworkId);
        return $this->showAjax();
    }

    public function actionPcSolutionBasicEdit() {
        $this->pageTitle = $this->t('solution', 'Edit PC Solution - Basic');
        // $this->pmps = $this->service->getPmps();
        return $this->actionSolutionBasicEdit (true);
    }

    public function actionPcSolutionTargetEdit() {
        $this->pageTitle = $this->t('solution', 'Edit PC Solution - Condition');
        $this->setConditionDicts();
        $solutionId = $this->I('solution_id');
        $solution = $this->M('Solution', $solutionId);
        $this->solution = $solution;
        $cityRank = $this->service->getRankCities();
        $this->cityRank = $cityRank;
        $this->clientAudienceType = $this->service->getAudienceWithClient();
        $youku = $this->service->getYouTuChannels('优酷');
        $tudou = $this->service->getYouTuChannels('土豆');
        $youTu = ['优酷频道' => $youku, '土豆频道' => $tudou];
        $this->youTu = ['优酷频道' => $youku, '土豆频道' => $tudou];
        if ($solutionId) {
            $this->S('solution_id', $solutionId);
            $weekday_slot = $this->M('Solution', $solutionId)['weekday_slot'];
            $weekday_slot = explode(',', $weekday_slot);
            $this->pauseWeekday = array_diff([0,1,2,3,4,5,6], $weekday_slot);
            $bwList = $this->service->getConditionBWList($solutionId, 'is_for_display');
            $this->bwList = $bwList;
            $conditions = $this->service->getConditionsKey($solutionId, 'is_for_display');
            $this->conditions = $conditions;
            $weather = array_shift($conditions['ConditionWeather']);
            $weather = str_replace(';', ',', $weather);
            $this->targetedWeather = explode(',', $weather);
            $this->bidCampaign = $this->M('Campaign', $solution['campaign_id']);
            if ($solution['type'] == 1) {
                $selectedChannels = $conditions['ConditionChannel'];
                !$selectedChannels && $selectedChannels[0] = '';
                $selectedChannels = explode(',', $selectedChannels[0]);
                $this->selectedChannels = $selectedChannels;
                $audience = $conditions['ConditionAudience'];
                !$audience && $audience[0]['audience_type_id'] = '';
                $targetedAudience = explode(',', $audience[0]['audience_type_id']);
                $this->targetedAudience = $targetedAudience;
                $retarget = $conditions['ConditionRetarget'];
                $retarget = array_pop($retarget);
                $this->targetedRetarget = $retarget;
            }
        }
        return $this->show();
    }

    public function actionPcSolutionResourceEdit() {
        $this->pageTitle = $this->t('solution', 'Edit PC Solution - Resource');
        $solutionId = $this->I('solution_id');
        $this->adNetworkId = $this->S('ad_network_id');
        $conditions = $this->service->getConditionsKey($solutionId, 'is_for_display');
        $this->bwList = $this->service->getConditionBWList($solutionId, 'is_for_display');
        $this->conditions = $conditions;
        $this->adspaces = $this->service->getAdspaces(0, 1);
        $solution = $this->service->M('Solution', $this->I('solution_id'));
        $this->solution = $solution;
        // $this->adnetworks = $this->getAll('AdNetwork', ['ad_network_type' => 1]);
        $this->adnetworks = $this->service->getAllAdNetWork();
        $this->solutionAdnets = array_column($this->getAll('ConditionAdspaceAdnetwork', ['solution_id' => $solutionId, 'status' => 1]) , 'adnetwork');
        $tmpVar = array_column($this->getAll('ConditionAdspaceAdnetwork', ['solution_id' => $solutionId, 'status' => 1]) , 'is_whitelist');
        $this->solutionAdspaceType = array_pop($tmpVar);
        $this->pmpAdspaces = $this->service->getPmpAdspaces($solution['pmp_guid']);
        return $this->show();
    }

    public function actionPcSolutionBiddingEdit() {
        $this->pageTitle = $this->t('solution', 'Edit PC Solution - Bidding');
        return $this->show();
    }

    public function actionPcSolutionCreativeEdit() {
        $this->pageTitle = $this->t('solution', 'Edit PC Solution - Creative');
        $this->solution_id = $this->I('solution_id');
        $this->solution = $this->M('Solution', $this->I('solution_id'));
        return $this->show();
    }

    public function actionUnbindSolutionCreative() {
        if ($this->I('type') == 'unlink') {
            $solutionId = $this->I('solution_id');
            $creativeId = $this->I('id');
            if (!is_numeric($solutionId) || !is_numeric($creativeId)) {
                $this->NG($this->t('solution', 'Need solution or creative id!'));
            }
            $unbind = $this->service->unbindCreative($solutionId, $creativeId);
            $this->service->updateSolutionTime($solutionId);
            if ($unbind) $this->OK($this->t('solution', 'Unbind creative successfully!'));
        }
    }

    public function actionGetAdnetworkAdspace() {
        $this->service->getAdNetworkAdspace();
    }

    public function actionGetReqs()
    {
        $solutionId = $this->I('solution_id');
        $cities = explode(',', $this->I('geoList'));
        $reqs = $this->service->getSolutionTargetedCityReqs($solutionId, $cities);
        $reqs = number_format($reqs);
        $this->ok(['traffic' => $reqs]);
    }
}// end of solution class declaration
